package com.study.intercept;

import java.util.HashSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.study.entity.db3.Account;

public class AuthenticateInterceptor implements HandlerInterceptor {

	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 在请求之前进行调用（Controller方法调用之前）
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return HandlerInterceptor.super.preHandle(request, response, handler);
		}

		// 获取uri
		String uri = request.getRequestURI();
		logger.info(uri);
		// 一些不需要过滤的方法
		

		// 统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
		HttpSession session = request.getSession();
		Account account = (Account) session.getAttribute("account");
		if (account != null) {
			logger.info(account.getRealName() + "uri====>>>" + uri);

			// /account/toList account/toList
			String substring = uri.substring(1);
			// account/toList account
			int index = substring.indexOf("/");
			if (index != -1) {
				// account
				substring = substring.substring(0, index);
			}
			@SuppressWarnings("unchecked")
			HashSet<String> urls = (HashSet<String>) session.getAttribute("module");

			// account是否在该用户所有有权限的资源中
			boolean result = urls.stream().anyMatch(substring::equals);

			if (!result) {
				response.sendRedirect("/");
			}
			return result;
		} else {
			response.sendRedirect("/");
			return false;
		}
	}

	/***
	 * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	/***
	 * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

}
